package com.qf.filter;

import com.qf.encoder.MD5PasswordEncoder;
import com.qf.encoder.PasswordEncoder;
import com.qf.pojo.User;
import com.qf.service.UserDetailService;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证过滤器，主要复杂登录认证的
 */
public class AuthenticationFilter implements HandlerInterceptor {

    UserDetailService userDetailService = new UserDetailService();

    //加密方式要和数据库的加密方式保持一致
    private PasswordEncoder encoder = new MD5PasswordEncoder();

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = userDetailService.loadByUsername(username);

        if (user == null){
            //用户名不对
            resp.sendRedirect("/login.html?msg=username error");

            return false;
        }else{
            //用户存在，比对密码 （数据库的密码可能是密文，我们比对时，需要对用户前台传递进来的密码进行加密）
            String encodePwd = encoder.encode(password);
            if (encodePwd.equals(user.getPassword())){
                //用户名密码正确，登录成功

                req.getSession().setAttribute("user",user);

                resp.sendRedirect("/index.html");

                return false;
            }else{
                //密码错误，登录失败
                resp.sendRedirect("/login.html?msg=password error");

                return false;
            }
        }
    }
}
